﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication5.Models;
using MvcPaging;

namespace MvcApplication5.Controllers
{
    public class NewsSiteController : Controller
    {
        private MvcApplication5Context db = new MvcApplication5Context();
        private const int DefaultPageSize = 10;
        //
        // GET: /NewsSite/

        public ViewResult Index(int? page, string type)
        {
            CreateStatistics();
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0; 
            IndexModel indexModel = new IndexModel();            
            if (type == "hot")
            {
                indexModel.News = db.News.Where(c => c.level == 8 && c.isHot == true).OrderByDescending(c => c.PublishedDate).ToPagedList(currentPageIndex, DefaultPageSize);
                indexModel.type = 1;
            }
            else
            {
                indexModel.News = db.News.Where(c => c.level == 8).OrderByDescending(c => c.PublishedDate).ToPagedList(currentPageIndex, DefaultPageSize);
                indexModel.type = 0;
            }            
            indexModel.Categories = db.Category;
            indexModel.Highlights = db.News.Where(c => c.position > 0 && c.position <= 5 && c.level == 8).OrderByDescending(c => c.PublishedDate);
            indexModel.Focus = db.News.Where(c => c.focus == true && c.level == 8).OrderByDescending(c => c.PublishedDate).Take(4);            
            var minDate = DateTime.Now.AddDays(-7);
            indexModel.MostViewed = db.News.Where(c => c.PublishedDate <= DateTime.Now && c.PublishedDate >= minDate && c.level == 8).OrderByDescending(c => c.ViewCount).Take(7); ;
            indexModel.Comments = db.Comment.OrderByDescending(c => c.Date).Take(6);
            indexModel.Advertisement = db.Advertisement.ToList();
            return View(indexModel);            
        }
        
        //
        //POST: /NewsSite/
        
        public ActionResult Search(string searchString, int? page)
        {
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            IndexModel indexModel = new IndexModel();
            var query = from item in db.News
                        where item.Title.Contains(searchString)
                        where item.level == 8
                        select item;
            indexModel.Categories = db.Category;
            indexModel.News = query.ToList<News>().ToPagedList(currentPageIndex, DefaultPageSize);
            indexModel.Comments = db.Comment.OrderByDescending(c => c.Date).Take(10);
            var minDate = DateTime.Now.AddDays(-7);
            indexModel.MostViewed = db.News.Where(c => c.PublishedDate <= DateTime.Now && c.PublishedDate >= minDate && c.level == 8).OrderByDescending(c => c.ViewCount).Take(7);
            ViewBag.searchString = searchString;
            return View(indexModel);
        }

        /*public ActionResult Index()
        {
            return View();
        }*/

        //
        //GET: /News/Details

        public ActionResult Details(int id) 
        {   
            DetailsModel detailsModel = new DetailsModel();
            List<News> newsList = new List<News>();
            List<Tag> tagList = new List<Tag>();
            News news = db.News.Find(id);
            news.ViewCount++;
            DateTime date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
            Statistics statistics1 = db.Statistics.Where(c => c.CategoryId == news.CategoryId && c.Date == date).First();
            Statistics statistics2 = db.Statistics.Where(c => c.Category.Tag.Contains(news.Category.Tag.Substring(0,4)) && c.Category.Tag.Length == 4 && c.Date == date).First();
            statistics1.ViewCount++;
            statistics2.ViewCount++;
            if (ModelState.IsValid)
            {
                db.Entry(news).State = EntityState.Modified;
                db.Entry(statistics1).State = EntityState.Modified;
                db.SaveChanges();
            }

            var temp = from detail in db.RelatedDetail
                              where detail.NewsId == id                              
                              select detail;            
            
            foreach (var item in temp){
                var relatedNews = from item1 in db.News
                                  where item1.NewsId == item.RelatedNewsId
                                  select item1;
                newsList.Add(relatedNews.First());
                
            }

            var query = from detail in db.TagDetail
                        where detail.NewsId == id
                        select detail;

            foreach (var item in query){
                var tags = from item1 in db.Tag
                          where item1.TagId == item.TagId
                          select item1;
                tagList.Add(tags.First());
            }

            detailsModel.News = news;
            detailsModel.relatedNews = newsList;
            detailsModel.tagList = tagList;
            detailsModel.Categories = db.Category.ToList();
            detailsModel.commentList = db.Comment.Where(c => c.NewsId == id && c.status == 1).OrderByDescending(c => c.Date).ToList();
            var minDate = DateTime.Now.AddDays(-7);
            detailsModel.MostViewed = db.News.Where(c => /*c.CategoryId == news.CategoryId &&*/ c.PublishedDate <= DateTime.Now && c.PublishedDate >= minDate && c.level == 8).OrderByDescending(c => c.ViewCount).Take(7);
            return View(detailsModel);
        }

        //
        //POST: /News/Details

        [HttpPost]
        public ActionResult Details(Comment comment, int id)
        {
            comment.NewsId = id;
            comment.Date = DateTime.Now;
            comment.status = 0;
            if (ModelState.IsValid)
            {
                db.Comment.Add(comment);
                db.SaveChanges();
                return RedirectToAction("Details");
            }
            return (Details(id));
        }

        //
        //GET: /New/Category

        public ActionResult Category(int? page, int id, string type)
        {
            var Category = db.Category.Find(id);            
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;            
            IndexModel indexModel = new IndexModel();
            if (type == "hot")
            {
                if (Category.Tag.Length == 8)
                {
                    indexModel.News = db.News.Where(c => c.level == 8 && c.isHot == true && c.CategoryId == id).OrderByDescending(c => c.PublishedDate).ToPagedList(currentPageIndex, DefaultPageSize);
                    indexModel.type = 1;
                }
                else
                {
                    var catList = (from item in db.Category
                                   where item.Tag.Substring(0, 4).Contains(Category.Tag) && item.Tag.Length == 8
                                   select item.CategoryId).ToList<int>();
                    indexModel.News = db.News.Where(c => c.level == 8 && c.isHot == true && catList.Contains(c.CategoryId.Value)).OrderByDescending(c => c.PublishedDate).ToPagedList(currentPageIndex, DefaultPageSize);
                    indexModel.type = 1;
                }
            }
            else
            {
                if (Category.Tag.Length == 8)
                {
                    indexModel.News = db.News.Where(c => c.level == 8 && c.CategoryId == id).OrderByDescending(c => c.PublishedDate).ToPagedList(currentPageIndex, DefaultPageSize);                    
                    indexModel.type = 0;
                }
                else
                {
                    var catList = (from item in db.Category
                                   where item.Tag.Substring(0, 4).Contains(Category.Tag) && item.Tag.Length == 8
                                   select item.CategoryId).ToList<int>();
                    indexModel.News = db.News.Where(c => c.level == 8 && catList.Contains(c.CategoryId.Value)).OrderByDescending(c => c.PublishedDate).ToPagedList(currentPageIndex, DefaultPageSize);                           
                    indexModel.type = 0;
                }
            }
                
            indexModel.Categories = db.Category;
            ViewBag.Id = id;
            if (Category.Tag.Length == 4)
            {
                ViewBag.Tag = "000" + id.ToString();
            }
            else
            {
                ViewBag.Tag = Category.Tag.Substring(0,4);
                ViewBag.subTag = Category.Tag;
            }

            indexModel.Highlights = db.News.Where(c => c.Category.Tag.Substring(0, 4) == Category.Tag.Substring(0,4) && c.level == 8).OrderByDescending(c => c.PublishedDate).Take(3);         
            var minDate = DateTime.Now.AddDays(-7);
            indexModel.MostViewed = db.News.Where(c => /*c.CategoryId == id &&*/ c.PublishedDate <= DateTime.Now && c.PublishedDate >= minDate && c.level == 8).OrderByDescending(c => c.ViewCount).Take(7);            
            indexModel.Comments = db.Comment/*.Where(c => c.News.CategoryId == id)*/.OrderByDescending(c => c.Date).Take(6);
            indexModel.Advertisement = db.Advertisement.ToList();
            return View(indexModel);
        }

        public ActionResult Tag(int id)
        {
            TagModel tagModel = new TagModel();
            List<News> newsList = new List<News>();            

            var temp = from detail in db.TagDetail
                              where detail.TagId == id                              
                              select detail;            
            
            foreach (var item in temp){
                var query = from item1 in db.News
                                  where item1.NewsId == item.NewsId
                                  select item1;
                newsList.Add(query.First());
                
            }
            tagModel.newsList = newsList;
            tagModel.Tag = db.Tag.Find(id);
            tagModel.Categories = db.Category.ToList();
            return View(tagModel);
        }

        public void CreateStatistics()
        {
            DateTime date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
            if (db.Statistics.Where(c => c.Date == date.Date).Count() == 0)
            {
                foreach (var item in db.Category.ToList())
                {
                    Statistics statistics = new Statistics();
                    statistics.Date = new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
                    statistics.CategoryId = item.CategoryId;
                    statistics.ViewCount = 0;
                    db.Statistics.Add(statistics);
                    db.SaveChanges();
                }
            }
        }

        public ActionResult Test()
        {
            return View();
        }
    }    
}
